
import numpy as np
import sys
import json
import sklearn.cluster as skc
import cv2

def doAnalysis(filename, errorRange):
    file = open(filename, encoding='utf-8')
    jsonset = json.load(file)
    dataset = []
    for i in range(len(jsonset)):
        data = []
        data.append(jsonset[i]["longitude"])
        data.append(jsonset[i]["latitude"])
        dataset.append(data)
    dataset = np.array(dataset, dtype=np.float32)
    # 将点进行聚类
    db = skc.DBSCAN(eps=float(errorRange) / 100000, min_samples=5).fit(dataset)
    core_samples_mask = np.zeros_like(db.labels_, dtype=bool)  # 设置一个样本个数长度的全false向量
    core_samples_mask[db.core_sample_indices_] = True #将核心样本部分设置为true
    labels = db.labels_
    unique_labels = set(labels)

    # 获取所有聚类的边界值
    area_list = []
    for k in zip(unique_labels):
        class_member_mask = (labels == k)  # 将所有属于该聚类的样本位置置为true
        xy = dataset[class_member_mask & core_samples_mask]  # 将所有属于该类的核心样本取出，使用大图标绘制
        if len(xy) == 0:
            continue

        # 获取轮廓的凸包
        hull_points = cv2.convexHull(xy)
        area_points = []
        # 小于3个点无法形成图形，需要过滤掉
        if len(hull_points) < 3:
            continue
        for i in range(len(hull_points)):
            area_point = {
                'longitude':hull_points[i][0][0],
                'latitude':hull_points[i][0][1]
            }
            area_points.append(area_point)

        # 补上第一个点，使之能形成闭环
        first_point = {
            'longitude':hull_points[0][0][0],
            'latitude':hull_points[0][0][1]
        }
        area_points.append(first_point)

        area = {
            'points' : area_points,
            'alarmCount' : len(xy)
        }

        area_list.append(area)

    return area_list

if __name__ == '__main__':
    filename = sys.argv[1]
    errorRange = sys.argv[2]
    area_list = doAnalysis(filename, errorRange)
    np.set_printoptions(threshold=sys.maxsize)
    print(area_list)